/*========================================================================
#   FileName: control.c
#     Author: lwd
#      Email: lwd_xinghuo@126.com
#   HomePage: 
# LastChange: 2013-04-18 09:58:35
#
# P_V function, implement process sync
========================================================================*/
#include <sys/sem.h>
#include <stdio.h>

#define SEM_KEY 0x112233

static int semid;

int init_pro_sync()
{
	printf("init P_V function!\n");
	semid = semget(SEM_KEY, 0, 0);
	if(semid == -1)
	{
		//semid = semget(IPC_PRIVATE, 1, IPC_CREAT|0666);
		semid = semget(SEM_KEY, 1, IPC_CREAT|0666);
		fprintf(stdout,"create sem successfull!semid = %d func:%s LINE:%d\n",\
			   	semid, __func__, __LINE__);
	}
#if 0	
	struct sembuf sbuf;
	sbuf.sem_num = 0;
	sbuf.sem_op  = 1;
	sbuf.sem_flg = 0;
#endif	
	if(semid == -1)
	{
		return 1;
	}
	else
	{
		return 0;
	}
}

int sync_P()
{
	//successful:return 0
	//failed:    return -1
//	printf("func: %s \n", __func__);
	struct sembuf sbuf;
	sbuf.sem_num = 0;
	sbuf.sem_op  = -1;
	sbuf.sem_flg = 0;
	
	if(semop(semid, &sbuf, 1) == -1)
	{
		return 1;
	}
	else
	{
		return 0;
	}
}

int sync_V()
{
//	printf("func: %s \n", __func__);
	struct sembuf sbuf;
	sbuf.sem_num = 0;
	sbuf.sem_op  = 1;
	sbuf.sem_flg = 0;
	
	if(semop(semid, &sbuf, 1) == -1)
	{
		return 1;
	}
	else
	{
		return 0;
	}
}
